from rest_framework import serializers
from .models import Comment,Notification,Message
from ctbloge.apps.accounts.serializers import UserNicknameSerializer
from django.contrib.contenttypes.models import ContentType
class CommentSerializer(serializers.ModelSerializer):
    content_type = serializers.SerializerMethodField()#获取评论的类型
    author = UserNicknameSerializer(read_only=True)
    children = serializers.SerializerMethodField()
    created_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    #获取父评论的用户名
    parent_author = serializers.ReadOnlyField(source='parent.author.nickname')
    article = serializers.SerializerMethodField()
    class Meta:
        model = Comment
        fields = ['id', 'article', 'author', 'content', 'parent', 'parent_author', 'created_date', 'children', 'content_type', 'likes_count']

    def get_children(self, obj):
        children = Comment.objects.filter(parent=obj)
        serializer = CommentSerializer(children, many=True)
        return serializer.data
    def get_content_type(self, obj):
            return ContentType.objects.get_for_model(obj.__class__).id
    def get_article(self, obj):
        return {
            'id': obj.article.id,
            'title': obj.article.title,}

class CommentCreateSerializer(serializers.ModelSerializer):
    author = serializers.SerializerMethodField()
    created_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    parent_author = serializers.ReadOnlyField(source='parent.author.nickname')
    class Meta:
        model = Comment
        fields = ['author', 'article', 'content', 'parent','parent_author','created_date',]

    def get_author(self, obj):
        return {
            'id': obj.author.id,
            'nickname': obj.author.nickname,
            'avatar': obj.author.avatar.url if obj.author.avatar else None
        }


class NotificationSerializer(serializers.ModelSerializer):
    # 添加系统通知专用字段展示
    class Meta:
        model = Notification
        fields = '__all__'
        extra_kwargs = {
            'sender': {'required': False},  # 系统通知允许无发送者
            'timestamp': {'read_only': True}
        }





class MessageSerializer(serializers.ModelSerializer):
    created_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    sender = UserNicknameSerializer(read_only=True)
    receiver = UserNicknameSerializer(read_only=True)
    class Meta:
        model = Message
        fields = '__all__'

class DanmuSerializer(MessageSerializer):
    sender_nickname = serializers.CharField(source='sender.nickname', read_only=True)
    sender_avatar = serializers.CharField(source='sender.avatar.url', read_only=True)

    class Meta:
        model = Message
        fields = ['id', 'content', 'sender_nickname','sender_avatar']